package com.liuya.base;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liuya.page.ResponseData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authz.UnauthorizedException;
import com.liuya.common.Constants;
import com.liuya.common.exception.BaseException;
import com.liuya.common.exception.IllegalParameterException;
import com.liuya.common.support.HttpCode;
import com.liuya.common.WebUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import java.util.Map;

/**
 * 基础控制器类
 *
 * @author liuya
 * @date 20160823
 */
public abstract class BaseController {
    protected final Logger logger = LogManager.getLogger(this.getClass());

    public static String basePath = "";

    /**
     * 获取当前用户Id
     */
    protected Object getCurrUser() {
        return WebUtil.getCurrentUser();
    }

    /**
     * 设置成功响应代码
     */
    protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap) {
        return setSuccessModelMap(modelMap, null);
    }

    /**
     * 设置成功响应代码
     */
    protected ResponseEntity<ModelMap> setSuccessModelMap(ModelMap modelMap, Object data) {
        return setModelMap(modelMap, HttpCode.OK, data);
    }

    /**
     * 设置响应代码
     */
    protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code) {
        return setModelMap(modelMap, code, null);
    }

    /**
     * 设置响应代码
     */
    protected ResponseEntity<ModelMap> setModelMap(ModelMap modelMap, HttpCode code, Object data) {
        modelMap.remove("void");
        if (data != null) {
            modelMap.put("data", data);
        }
        modelMap.put("httpCode", code.value());
        modelMap.put("msg", code.msg());
        modelMap.put("timestamp", System.currentTimeMillis());
        modelMap.put("basePath", getBasePath());
        return ResponseEntity.ok(modelMap);
    }

    public ModelAndView request(String path) {
        ModelAndView view = new ModelAndView(path);
        view.addObject("basePath", BaseController.getBasePath());
        return view;
    }

    public ModelAndView request(ResponseData data) {
        String page = data.getTemplet()!=null ? data.getTemplet(): data.getPage();
        ModelAndView view = new ModelAndView(page , "data", data);
        if(data.getTemplet()!=null && data.getPage()!=null){
            view.addObject("page", data.getPage()) ;
        }
        view.addObject("basePath", BaseController.getBasePath()) ;
        return view ;
    }

    public ModelAndView request(ResponseData data , Map<String, Object> dataMap) {
        dataMap.put("data", data) ;
        ModelAndView view = new ModelAndView(data.getPage() , dataMap);
        view.addObject("basePath", BaseController.getBasePath());

        return view;
    }

    /**
     * 重定向
     * @param redirectView
     * @return
     */
    public ModelAndView redirect(RedirectView redirectView) {
        return new ModelAndView(redirectView);
    }

    public ModelAndView redirect(String url) {
        RedirectView redirectView = new RedirectView(url);
        return new ModelAndView(redirectView);
    }

    /**
     * 异常处理
     */
    @ExceptionHandler(Exception.class)
    public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception {
        logger.error(Constants.Exception_Head, ex);
        ModelMap modelMap = new ModelMap();
        if (ex instanceof BaseException) {
            ((BaseException) ex).handler(modelMap);
        } else if (ex instanceof IllegalArgumentException) {
            new IllegalParameterException(ex.getMessage()).handler(modelMap);
        } else if (ex instanceof UnauthorizedException) {
            setModelMap(modelMap, HttpCode.FORBIDDEN);
        } else {
            setModelMap(modelMap, HttpCode.INTERNAL_SERVER_ERROR);
        }
        request.setAttribute("msg", modelMap.get("msg"));
        response.setContentType("application/json;charset=UTF-8");
        byte[] bytes = JSON.toJSONBytes(modelMap, SerializerFeature.DisableCircularReferenceDetect);
        response.getOutputStream().write(bytes);
    }

    /**
     * 创建 模型管理的模板页面
     * @param page
     * @return
     */
    public ResponseData createDMTempletResponse(String page) {
        return new ResponseData("/pages/datamodel/index" , page);
    }

    /**
     *
     * @param page
     * @return
     */
    public ResponseData createResponse(String page) {
        return new ResponseData(page);
    }

    public static String getBasePath() {
        return basePath;
    }

    public static void setBasePath(String basePath) {
//        if(basePath.endsWith("/"))
            BaseController.basePath = basePath;
//        else {
//            BaseController.basePath = basePath + "/";
//        }

    }
}
